//
//  LoginAndViewController.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/4/17.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class LoginAndViewController: NSViewController {
    let otherImages:[String] = ["icon_wechat"]
    let kWidth_Other = CGFloat(40)
    let kSpace_Other = CGFloat(30)
    
    var isAgreePtl:Bool = true {
        didSet {
            
        }
    }
    
    
    var isPwd:Bool = true {
        didSet {
            self.loginPwd.isHidden = !isPwd
            self.loginVer.isHidden = isPwd
        }
    }
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kHomeWinWidth, kHomeWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
    }
    
    func setupUI() {
        self.view.layer?.backgroundColor = color_gray(255).cgColor
        
        
        self.view.addSubview(showImageV)
        showImageV.snp.makeConstraints { (make) in
            make.size.equalTo(showImageV.image!.size)
            make.top.equalTo(12)
            make.right.equalTo(-50)
        }
        
        self.view.addSubview(qrBtn)
        qrBtn.snp.makeConstraints { (make) in
            make.size.equalTo(qrBtn.image!.size)
            make.right.top.equalToSuperview()
        }
        
      
        self.view.addSubview(otherBtns)
        otherBtns.snp.makeConstraints { (make) in
            make.width.equalTo(self.othersWidth())
            make.height.equalTo(kWidth_Other+10)
            make.bottom.equalTo(-60)
            make.centerX.equalToSuperview()
        }
        self.initOthers(inView: otherBtns)
        
        let labWidth = UserInfoManager.shared.lang=="en" ? 240:180
        self.view.addSubview(proLab)
        proLab.snp.makeConstraints { (make) in
            make.width.equalTo(labWidth)
            make.centerX.equalToSuperview().offset(10)
            make.height.equalTo(20)
            make.bottom.equalTo(-30)
        }
        self.view.addSubview(proBtn)
        proBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(12)
            make.right.equalTo(proLab.snp.left).offset(-2)
            make.centerY.equalTo(proLab)
        }
        
        self.view.addSubview(loginPwd)
        loginPwd.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-100)
            make.centerX.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalTo(200)
        }
        
        self.view.addSubview(loginVer)
        loginVer.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-100)
            make.centerX.equalToSuperview()
            make.height.equalTo(80)
            make.top.equalTo(200)
        }
        
        self.view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-100)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
            make.top.equalTo(loginPwd.snp.bottom).offset(50)
        }
        
        let wi = roleBtn.title.ga_Size(with: 12).width
        self.view.addSubview(roleBtn)
        roleBtn.snp.makeConstraints { (make) in
            make.top.equalTo(loginPwd.snp.bottom).offset(10)
            make.width.equalTo(wi+20)
            make.right.equalTo(loginPwd)
            make.height.equalTo(20)
        }
        
    }
    
    lazy var showImageV: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.imageNamed("icon_login_bn")!)
        return imageV
    }()
    
    lazy var qrBtn: ZHButton = {
        let btn = ZHButton()
        btn.normalImage = NSImage.imageNamed("icon_login_qr")!
        btn.target = self
        btn.action = #selector(qrBtnAction(senber:))
        return btn
    }()
    
    lazy var loginBtn: ZHButton = {
        let btn = ZHButton.init(frame: NSRect.zero)
        btn.zh_title = "登录".localized()
        btn.zh_font = NSFont.boldSystemFont(ofSize: 14)
        btn.zh_color = color_gray(255)
        btn.zh_backgroundColor = color_main108
        btn.hasBorder = true
        btn.zh_cornerRadius = 5
        btn.target = self
        btn.action = #selector(loginBtnAction(senber:))
        return btn
    }()
    
    lazy var roleBtn: ZHButton = {
        let btn = ZHButton.init(frame: NSRect.zero)
        btn.zh_title = "验证码登录".localized()
        btn.zh_font = NSFont.systemFont(ofSize: 14)
        btn.hasBorder = true
        btn.zh_color = color_gray(140)
        btn.zh_backgroundColor = NSColor.clear
        btn.target = self
        btn.action = #selector(roleBtnAction(senber:))
        return btn
    }()
    
    lazy var otherBtns: NSView = {
        let view = NSView()
        return view
    }()
    
    func othersWidth() -> CGFloat {
        return (kSpace_Other+kWidth_Other)*CGFloat(otherImages.count)-kSpace_Other
    }
    
    func initOthers(inView:NSView) {
        for (inx,val) in otherImages.enumerated() {
            let btn = ZHButton()
            btn.normalImage = NSImage.imageNamed(val)!
            btn.title = ""
            btn.hasBorder = true
            btn.zh_borderColor = color_gray(200)
            btn.zh_borderWidth = 1.0
            btn.zh_cornerRadius = kWidth_Other/2
            btn.zh_backgroundColor = color_gray(255)
            btn.backgroundHoverColor = color_gray(235)
            btn.tag = 100+inx
            btn.target = self
            btn.action = #selector(otherAction(senber:))
            inView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(kWidth_Other)
                make.centerY.equalToSuperview()
                make.left.equalTo(CGFloat(inx)*(kSpace_Other+kWidth_Other))
            }
            
        }
    }
    
    lazy var proLab: NSTextField = {
        let lab = NSTextField.init(frame: NSRect.zero)
        let informstring = NSMutableAttributedString()
        let normlstring = NSMutableAttributedString.init(string: "登录即同意".localized())
        let hyperString = NSAttributedString.init(string: "服务条款".localized(), attributes: [NSAttributedString.Key.link:"http://www.1meeting.cn/agreement"])
        let prltring = NSMutableAttributedString.init(string: "、"+"隐私协议".localized())
        informstring.append(normlstring)
        informstring.append(hyperString)
        informstring.append(prltring)
        informstring.addAttributes([NSAttributedString.Key.font:NSFont.systemFont(ofSize: 12)], range: NSRange.init(0..<informstring.length))
        lab.attributedStringValue = informstring
        
        lab.backgroundColor = NSColor.clear
        lab.alignment = .center
        lab.isEditable = false
        lab.isBordered = false
        lab.isSelectable = true
        lab.allowsEditingTextAttributes = true
        return lab
    }()
    
    lazy var proBtn: ZHButton = {
        let btn = ZHButton()
        btn.canSelected = true
        btn.normalImage = NSImage.imageNamed("icon_pro_agree")!
        btn.selectedImage = NSImage.imageNamed("icon_pro_noagree")!
        btn.action = #selector(proBtnAction(senber:))
        btn.target = self
        return btn
    }()
    
    lazy var loginPwd: LoginPwdView = {
        let view  = LoginPwdView()
        return view
    }()
    
    lazy var loginVer: LoginVerView = {
        let view  = LoginVerView()
        view.isHidden = true
        return view
    }()
   
}

extension LoginAndViewController {
    
    @objc func proBtnAction(senber:ZHButton) {
        self.isAgreePtl = !self.isAgreePtl
    }
    
    @objc func roleBtnAction(senber:ZHButton)  {
        self.isPwd = !self.isPwd
        let text = self.isPwd ? "验证码登录":"账号密码登录"
        self.roleBtn.zh_title = text.localized()
        let image = self.isPwd ? "icon_login_bn":"icon_login_bnpwd"
        self.showImageV.image = NSImage.imageNamed(image)
        let width = text.localized().ga_Size(with: 14).width
        self.roleBtn.snp.updateConstraints { (make) in
            make.width.equalTo(width+5)
        }
    }
    
    @objc func qrBtnAction(senber:ZHButton) {
        guard let loginVc = self.view.superview?.jk_viewController() as? LoginViewController else {
            return
        }
        loginVc.switchTo(vc: loginVc.children[1])
    }
    
    @objc func loginBtnAction(senber:ZHButton) {
        if self.isAgreePtl==false {
            show_msg("请同意相关服务条款".localized())
            return
        }
        
        if isPwd == true {
            self.loginWithPwd()
        }else {
            self.loginWithVertify()
        }
        
    }
    
    func loginWithVertify()  {
        let phoneText = self.loginVer.anoView.zhTEF.textField.stringValue
        let phone = phoneText.clearId()
        let verifyText = self.loginVer.pwdView.zhTEF.textField.stringValue
        
        if String.validatedPhone(phoneStr:phone) == true && verifyText.count>0 {
            HUD.show()
            NetEngine.reponse_checkdtm(phone: Int(phone)!, nextzym: Int(verifyText)!, success: { (mode) in
                HUD.dismiss()
                RtcEngine.saveLoginData(mode: mode)
                UserInfoManager.shared.isLogin = true
                NotificationCenter.default.post(name: MTLoginStateNotification, object: nil)
                self.view.window?.close()
            }) {
                HUD.dismiss()
            }
        }else {
            show_msg("输入有误，请从新输入".localized())
        }
    }
    
    func loginWithPwd() {
        let acc = self.loginPwd.anoView.zhTEF.textField.stringValue
        let pwd = self.loginPwd.pwdView.zhTEF.isVisiblePwd ? self.loginPwd.pwdView.zhTEF.secureTextField.stringValue: self.loginPwd.pwdView.zhTEF.textField.stringValue
        HUD.show()
        if acc.count>0 && pwd.count>0 {
            NetEngine.reponse_userPwdlogin(username: acc, password: pwd, success: { (mode) in
                HUD.dismiss()
                RtcEngine.saveLoginData(mode: mode)
                UserInfoManager.shared.isLogin = true
                NotificationCenter.default.post(name: MTLoginStateNotification, object: nil)
                self.view.window?.close()
            }) {
                HUD.dismiss()
            }
        }
    }
    
    @objc func otherAction(senber:ZHButton)  {
        switch senber.tag {
        case 100:
            guard let loginVc = self.view.superview?.jk_viewController() as? LoginViewController else {
                return
            }
            loginVc.switchTo(vc: loginVc.children[1])
        default:
            break
        }
    }
}
